package com.chengcang.admin.modules.log.binlog;

import cn.hutool.core.util.StrUtil;
import com.chengcang.admin.modules.log.binlog.model.BinLogItem;
import com.chengcang.admin.modules.log.binlog.model.BinlogConfig;
import com.chengcang.admin.modules.log.binlog.model.Column;
import com.chengcang.admin.modules.sys.dao.DdlBaseMapper;
import com.github.shyiko.mysql.binlog.event.EventType;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.Serializable;
import java.sql.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author fankunfeng
 * @date 2023-01-31 10:47:46
 **/
@Slf4j
public class BinLogUtils {

    /**
     * 拼接dbTable
     */
    public static String getdbTable(String db, String table) {
        return db + "-" + table;
    }

    /**
     * 根据DBTable获取table
     *
     * @param dbTable
     * @return java.lang.String
     */
    public static String getTable(String dbTable) {
        if (StrUtil.isEmpty(dbTable)) {
            return "";
        }
        String[] split = dbTable.split("-");
        if (split.length == 2) {
            return split[1];
        }
        return "";
    }

    /**
     * 将逗号拼接字符串转List
     *
     * @param str
     * @return
     */
    public static List<String> getListByStr(String str) {
        if (StrUtil.isEmpty(str)) {
            return Lists.newArrayList();
        }

        return Arrays.asList(str.split(","));
    }

    /**
     * 根据操作类型获取对应集合
     *
     * @param binLogItem
     * @return
     */
    public static Map<String, Serializable> getOptMap(BinLogItem binLogItem) {
        // 获取操作类型
        EventType eventType = binLogItem.getEventType();
        if (EventType.isWrite(eventType) || EventType.isUpdate(eventType)) {
            return binLogItem.getAfter();
        }
        if (EventType.isDelete(eventType)) {
            return binLogItem.getBefore();
        }
        return null;
    }

    /**
     * 获取操作类型
     *
     * @param binLogItem
     * @return
     */
    public static String getOptType(BinLogItem binLogItem) {
        // 获取操作类型
        EventType eventType = binLogItem.getEventType();
        if (EventType.isWrite(eventType)) {
            return "保存";
        }
        if (EventType.isUpdate(eventType)) {
            return "修改";
        }
        if (EventType.isDelete(eventType)) {
            return "删除";
        }
        return null;
    }
}
